import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/RouteAct.dart';
import '../http/api.dart';
import 'ShipperAuth.dart';

class FaceCheckView extends StatefulWidget {
  const FaceCheckView({super.key, required this.url, required this.Type, required this.userMap});
  final String url;
  final int Type;
  //用户信息
  final Map userMap;
  @override
  State<FaceCheckView> createState() => _FaceCheckViewState();
}

class _FaceCheckViewState extends State<FaceCheckView> {
  @override
  late PullToRefreshController pullToRefreshController;
  InAppWebViewController? webViewController;
  @override

  void initState() {
    // TODO: implement initState
    super.initState();
    requestCameraPermission();
    pullToRefreshController =PullToRefreshController(
      options: PullToRefreshOptions(
        color: Colors.blue,
      ),
      onRefresh: ()async{
        if(Platform.isAndroid){
          webViewController?.reload();
        }else if(Platform.isIOS){
          webViewController?.loadUrl(urlRequest: URLRequest(
            url: await webViewController?.getUrl()
          ));
        }
      }
    );
  }
  ///加载 Html 的回调
  ///[code]消息类型标识
  ///[msg] 消息内容
  ///[content] 回传的参数
  void callBack(int ?code, String ?msg, content) {
    //加载页面完成后 对页面重新测量的回调
    //这里没有使用到
    //当FaiWebViewWidget 被嵌套在可滑动的 widget 中，必须设置 FaiWebViewWidget 的高度
    //设置 FaiWebViewWidget 的高度 可通过在 FaiWebViewWidget 嵌套一层 Container 或者 SizeBox
    if (code == 201) {
      //页面加载完成后 测量的 WebView 高度
      double webViewHeight = content;
      print("webViewHeight " + webViewHeight.toString());
    } else {
      //其他回调
    }
    setState(() {
      print("回调：code[" + code.toString() + "]; msg[" + msg.toString() + "]");
    });
  }
  Future<void> requestCameraPermission() async {

    if (Platform.isAndroid) {
      var status = await Permission.camera.status;
      if (status.isGranted) {
        // 相机权限已被授予
        // 这里可以执行需要相机权限的操作，比如启动相机拍照

      } else if (status.isDenied) {
        // 相机权限被拒绝，但用户可以再次授权
        status = await Permission.camera.request();
        if (status.isGranted) {
          // 用户同意了相机权限
          // 这里可以执行需要相机权限的操作，比如启动相机拍照

        } else {
          // 用户拒绝了相机权限，无法使用相机功能
          // 可以在此处展示信息提示用户需要权限

        }
      } else if (status.isPermanentlyDenied) {
        // 相机权限被永久拒绝，需要用户手动开启权限
        openAppSettings();
      }
    }
  }
  String url = "";
  double progress = 0;
  late InAppWebViewController webView;
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
        appBar: AppBar(
        centerTitle: true,
          backgroundColor: Colors.grey[200],
        title: Text("人脸识别",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
        ),

      body: Container(
        child: Column(
          children: <Widget>[

            Expanded(
              child: Container(
                child: InAppWebView(
                  initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
                  initialOptions: InAppWebViewGroupOptions(
                    android: AndroidInAppWebViewOptions(),
                    ios: IOSInAppWebViewOptions(
                      allowsInlineMediaPlayback:true,
                    ),
                    // crossPlatform: InAppWebViewOptions(
                    //   javaScriptEnabled: true,
                    //   mediaPlaybackRequiresUserGesture: false,
                    // ),
                  ),
                  onWebViewCreated: (InAppWebViewController controller) {
                    webView = controller;
                    webView.addJavaScriptHandler(handlerName: 'handlerIdent', callback: (args) {
                      print("JS to Native event received: ${args[0]}");
                      if(args[0].toString()=="1"){

                          ApiManager.postData(
                            context,
                            'api/auth/shipper/user/editPersonalInfo',
                            {
                              "id": widget.userMap['id'],
                              "companyId": 0,
                              "phoneNum": widget.userMap['phoneNum'],
                              "realName": widget.userMap['realName'],
                              "idNum": widget.userMap['idNum'],
                              "address": widget.userMap['address'],
                              "validFrom": widget.userMap['validFrom'],
                              "validTo": widget.userMap['validTo'],
                              "frontPath":widget.userMap['frontPath'],
                              "backPath": widget.userMap['backPath'],
                              "authStatus": 0,
                              "status": 0,
                              "faceSuccess":1
                            },
                                (responseData) {
                              setState(() {
                                if (widget.Type == 1) {
                                  Navigator.push(context,
                                      MaterialPageRoute(builder: (context) {
                                        return ShipperAuth(token: "",);
                                      }));
                                }else {
                                  Navigator.pop(context, "success");
                                  Navigator.pop(context, "success");
                                }
                              });
                            },
                          );

                      }else  if(args[0].toString()=="2"){
                        setState(() {
                          webView.loadUrl(urlRequest: URLRequest(url: Uri.parse(widget.url)));
                        });
                      }else{
                        Navigator.pop(context);
                        // Navigator.pop(context,"success");
                      }

                    });
                  },
                  androidOnPermissionRequest: (InAppWebViewController controller, String origin, List<String> resources) async {
                    return PermissionRequestResponse(resources: resources, action: PermissionRequestResponseAction.GRANT);//主要是这行代码是授权的
                  },
                  onLoadStart: (controller, url) {
                    setState(() {
                      this.url = url.toString();
                    });
                  },
                  onLoadStop: (controller, url) async {
                    setState(() {
                      this.url = url.toString();
                    });
                  },
                  onProgressChanged: (controller, progress) {
                    if (progress == 100) {
                      // Page finished loading
                    }
                    setState(() {
                      this.progress = progress / 100;
                    });
                  },
                  onConsoleMessage: (controller, consoleMessage) {
                    print(consoleMessage); // Useful for debugging JavaScript code
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
